const BASE_URL: string = 'https://yzm-api-test.56yzm.com';
import http from '@ohos.net.http';
import PreferenceUtil from '../ets/common/utils/PreferenceUtil';
import { AppStorageV2, UIContext } from '@kit.ArkUI';

export async function httpRequestPost(url: string, body: {}, requestSuccess: Function, requestFail: Function) {
  let result = new ResponseResult(0, 'info', new Map<string, any>())
  url = BASE_URL + url
  let httpRequest = http.createHttp();
  let header = {};
  let token = await PreferenceUtil.get(PreferenceUtil.token, '')
  if (token != null && token != '') {
    header['token'] = token
  }
  console.log('POST请求入参 => URL:', BASE_URL + url);
  console.log('POST请求入参 => header:', JSON.stringify(header));
  console.log('POST请求入参 => Body:', JSON.stringify(body));
  await httpRequest.request(
    url,
    {
      method: http.RequestMethod.POST,
      extraData: body,
      header: header,
    },
  ).then((res) => {
    handleResponse(result, res, requestSuccess, requestFail)
  }).catch((err) => {
    console.error('POST请求异常 => 错误信息:', JSON.stringify(err));
    let error = new ResponseError(0, '请求异常!')
    requestFail(error)
  })
}

export function httpRequestDel(url: string) {
  url = BASE_URL + url
  let httpRequest = http.createHttp();
  var header = {
    'Content-Type': 'application/json',
  }
  let responseResult = httpRequest.request(url, {
    method: http.RequestMethod.DELETE,
    header: header
  });
  return responseResult
}


export function httpRequestPut(url: string, params: any) {
  url = BASE_URL + url
  let httpRequest = http.createHttp();
  var header = {
    'Content-Type': 'application/json',
  }
  let responseResult = httpRequest.request(url, {
    method: http.RequestMethod.PUT,
    extraData: params,
    header: header
  });
  return responseResult
}

export function httpRequestGet(url: string, query: any) {
  url = BASE_URL + url + query
  let httpRequest = http.createHttp();
  var header = {
    'Content-Type': 'application/json',
  }
  let responseResult = httpRequest.request(url, {
    method: http.RequestMethod.GET,
    header: header
  });
  return responseResult
}

// 网络请求返回信息通用
function handleResponse(
  result: ResponseResult,
  response: http.HttpResponse,
  requestSuccess: Function,
  requestFail: Function,
) {
  console.log('POST请求响应 => 状态码:', response.responseCode);
  console.log('POST请求响应 => 返回结果:', JSON.stringify(JSON.parse(response.result as string)));
  // 网络请求错误相关异常
  if (response.responseCode != http.ResponseCode.OK) {
    let error = new ResponseError(0, '接口异常!')
    error.errorCode = response.responseCode
    requestFail(error)
    return;
  }
  // 解析数据
  result = JSON.parse(response.result as string)
  // 返回的业务异常
  if (result.code != 200) {
    if (result.code == 401) {
      let error = new ResponseError(401, '当前登录已失效，请重新登录')
      requestFail(error)
      const context = AppStorageV2.connect(UIContext, 'uiContext', () => new UIContext());
      PreferenceUtil.logout(context)
      return;
    }
    let error = new ResponseError(0, '接口异常!')
    error.errorCode = result.code
    error.errorMsg = result.msg ?? ''
    requestFail(error)
    return;
  }
  // 返回成功
  requestSuccess(result)
}

export class ResponseResult {
  code: number
  msg: string
  data: object

  constructor(code: number, msg: string, data: object) {
    this.code = code;
    this.msg = msg;
    this.data = data;
  }
}

export class ResponseError {
  errorCode: number
  errorMsg: string

  constructor(errorCode: number, errorMsg: string) {
    this.errorCode = errorCode;
    this.errorMsg = errorMsg;
  }
}

export class ApiUrl {
  // 获取验证码
  static readonly loginCaptchaSend: string = '/mobile/account/loginCaptchaSend';
  // 验证码登录
  static readonly captchaLogin: string = '/mobile/account/captchaLogin';
  // 获取用户信息
  static readonly getUserInfo: string = '/mobile/account/info';
}
